#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>

#include "beacon.h"
#include "common.h"
#include "readConfig.h"

void beacon(int randint)
{
	char buff[BUFFERSIZE];
	int so_broadcast = 1;

	//获取socket
	int sockfd = Socket(AF_INET, SOCK_DGRAM, 0);
	Setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast));

	//从配置文件读取广播地址
	Config configSettings(ConfigFile);
	std::string BROADCASTADDR;
	int BROADCASTPORT;
	BROADCASTADDR = configSettings.Read("BROADCASTADDR", BROADCASTADDR);
	BROADCASTPORT = configSettings.Read("BROADCASTPORT", BROADCASTPORT);

	//格式化广播地址
	struct sockaddr_in broadcast_addr;
	bzero(&broadcast_addr, sizeof(broadcast_addr));
	broadcast_addr.sin_family = AF_INET;
	broadcast_addr.sin_port = htons(BROADCASTPORT);
	broadcast_addr.sin_addr.s_addr = inet_addr(BROADCASTADDR.c_str());
	
	//将randint填入buff中
	bzero(buff, sizeof(buff));
	buff[0] = 0x01;
	int len = sprintf(buff + 1, "%d", randint);

	//发送广播
	Sendto(sockfd, buff, 1 + len, 0, (SA *)&broadcast_addr, sizeof(SA));
	
	//关闭socket
	Close(sockfd);
}
